package com.tepth.busfix.main.repair;

import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.util.SparseArray;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.LinearLayout;

import com.chad.library.adapter.base.BaseQuickAdapter;
import com.chad.library.adapter.base.listener.OnItemClickListener;
import com.google.gson.Gson;
import com.tepth.busfix.R;
import com.tepth.busfix.adapter.RepairOperatorAdapter;
import com.tepth.busfix.adapter.RepairTypeAdapter;
import com.tepth.busfix.base.OkBus;
import com.tepth.busfix.bean.reponse.BusInfo;
import com.tepth.busfix.bean.reponse.FaultSection;
import com.tepth.busfix.bean.reponse.Person;
import com.tepth.busfix.bean.reponse.Process;
import com.tepth.busfix.bean.reponse.ProcessDecorate;
import com.tepth.busfix.bean.reponse.Repair;
import com.tepth.busfix.bean.reponse.Trouble;
import com.tepth.busfix.bean.reponse.TroubleClassification;
import com.tepth.busfix.bean.reponse.TroubleContent;
import com.tepth.busfix.bean.request.RepairInfo;
import com.tepth.busfix.config.SpKey;
import com.tepth.busfix.data.DataProvider;
import com.tepth.busfix.event.DataClearEvent;
import com.tepth.busfix.event.RepairDataRefreshEvent;
import com.tepth.busfix.ic.IcManager;
import com.tepth.busfix.ic.OpenIcEvent;
import com.tepth.busfix.main.chooseoperator.ChooseOperatorActivity;
import com.tepth.busfix.main.home.HomeActivity;
import com.tepth.busfix.main.login.LoginActivity;
import com.tepth.busfix.main.partsearch.PartSearchActivity;
import com.tepth.busfix.main.repair.complete.CompletePunchCardActivity;
import com.tepth.busfix.tools.AESUtils;
import com.tepth.busfix.tools.SPUtils;
import com.tepth.busfix.tools.ToastUtils;
import com.tepth.busfix.tools.UsbUtil;
import com.tepth.busfix.view.ChooseOperatorDialog;
import com.tepth.busfix.view.dialog.DialogDelegate;
import com.tepth.busfix.view.dialog.SweetAlertDialogDelegate;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;

import java.util.ArrayList;
import java.util.Calendar;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import butterknife.Unbinder;

/**
 * Created by zhangyu on 2017/9/6.
 */

public class ContentFragment extends Fragment implements RepairContract.View {
    public static final String EXTRA_NAME = "busInfo";
    public static final int ITEM_SELECT_BUS_TAG = 1;
    private static final int REQUEST_CARD_WORK = 2;
    private static final int REQUEST_CARD_PASS = 3;
    private static final int REQUEST_CARD_CANCEL = 5;
    //打卡类型
    private int mRequestCode;

    public static ContentFragment newInstance(BusInfo busInfo, boolean show) {
        ContentFragment fragment = new ContentFragment();
        Bundle bundle = new Bundle();
        bundle.putSerializable(EXTRA_NAME, busInfo);
        bundle.putBoolean("show", show);
        fragment.setArguments(bundle);
        return fragment;
    }

    @BindView(R.id.recycler_view_type)
    RecyclerView recyclerViewType;
    @BindView(R.id.recycler_view_tool)
    RecyclerView recyclerViewTool;
    @BindView(R.id.swipeLayout_type)
    SwipeRefreshLayout mSwipeRefreshLayoutType;
    @BindView(R.id.swipeLayout_tool)
    SwipeRefreshLayout mSwipeRefreshLayoutTool;
    @BindView(R.id.btn_work_device)
    Button btnWorkDevice;
    @BindView(R.id.layout_device)
    LinearLayout layoutDevice;
    @BindView(R.id.btn_custom_add)
    Button mBtnCustomAdd;
    Unbinder mUnBinder;

    /**
     * 用于查询的车辆信息
     */
    BusInfo busInfo;
    /**
     * 下面显示的已打卡操作列表列表
     */
    private List<TroubleContent> troubleContents = new ArrayList<>();
    private RepairOperatorAdapter operatorAdapter;
    private DialogDelegate dialogDelegate;
    private RepairPresenter mPresenter;
    //打卡操作列表
    private SparseArray<List<TroubleContent>> mClockInData = new SparseArray<>();
    //打卡提交的信息
    private Repair repair;
    private RepairInfo repairInfo;
    private RepairTypeAdapter mTypeAdapter;
    private Trouble mCurrentTrouble;
    private TroubleContent mCurrentCancelPunch;
    private boolean isCanOperator;
    private ArrayList<Long> mHasCompleteTroubleList = new ArrayList<>();
    private PunchState mPunchState = PunchState.passCheck;
    private enum PunchState{
        cancel,
        work,
        passCheck,
    }

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        View rootView = inflater.inflate(R.layout.fragment_content, container, false);
        mUnBinder = ButterKnife.bind(this, rootView);
        initView();
        return rootView;
    }

    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        Bundle bundle = getArguments();
        if (bundle != null) {
            busInfo = (BusInfo) bundle.getSerializable(EXTRA_NAME);
            isCanOperator = bundle.getBoolean("show");
        }

    }

    public void initView() {
        setPresenter();
        setCanOperator(isCanOperator);
        dialogDelegate = new SweetAlertDialogDelegate(getActivity());
        refreshData();
        EventBus.getDefault().register(this);
        initRecyclerView();
        initSpData();
    }


    /**
     * 在竣检返工那里被勾选了的表示问题解决了，这个问题就不能再操作了
     * 这是个问题解决的id列表，点击问题的时候进行判断
     */
    private void initSpData() {
        ArrayList<Long> list = (ArrayList<Long>) SPUtils.getObject(getActivity(), "completeTroubleList");
        if (list != null) {
            mHasCompleteTroubleList.addAll(list);
        }
    }

    private void refreshData() {
        mPresenter.getRepair();
        if(dialogDelegate.getDialog() != null && dialogDelegate.getDialog().isShowing()){
            dialogDelegate.changeText("打卡成功","正在刷新...");
        }else {
            dialogDelegate.showProgressDialog(true, getString(R.string._loading));
        }
    }

    private void initRecyclerView() {
        mSwipeRefreshLayoutType.setEnabled(false);
        mSwipeRefreshLayoutTool.setEnabled(false);
        recyclerViewType.setLayoutManager(new LinearLayoutManager(getActivity()));
        mTypeAdapter = new RepairTypeAdapter(getActivity(), R.layout.item_repair_content,
                R.layout.item_repair_head, new ArrayList<FaultSection>()
                , new RepairTypeAdapter.OnTagClickListener() {
            @Override
            public void onTagClick(Trouble trouble) {
                if (isCanOperator) {
                    if (mHasCompleteTroubleList.contains(trouble.getId())) {
                        ToastUtils.showToast(getActivity(), "已经竣检通过的作业项不能操作!");
                    } else {
                        List<Process> processList = trouble.getProcessList();
                        mCurrentTrouble = trouble;
                        if (processList == null) {
                            dialogDelegate.showProgressDialog(true, "正在加载...");
                            mPresenter.getProcess();
                        } else {
                            showSelectOperatorDialog(processList);
                        }
                    }
                }
            }
        });
        recyclerViewType.setAdapter(mTypeAdapter);

        recyclerViewTool.setLayoutManager(new LinearLayoutManager(getActivity()));
        recyclerViewTool.addOnItemTouchListener(new OnItemClickListener() {

            @Override
            public void onItemLongClick(final BaseQuickAdapter adapter, View view, final int position) {
                final TroubleContent troubleContent = (TroubleContent) adapter.getItem(position);
                if (!troubleContent.isRework() && isCanOperator && troubleContent.getWorkPerson() != null) {//只有不是返工状态且没有竣检完成才可以取消打卡
                    if (!mHasCompleteTroubleList.contains(troubleContent.getTroubleId())) {
                        //竣检勾选的作业项不能取消打卡
                        dialogDelegate.showWarningDialog("取消打卡", "确认执行此操作么?", new DialogDelegate.OnDialogListener() {
                            @Override
                            public void onClick() {
                                mCurrentCancelPunch = troubleContent;
                                if (UsbUtil.hasUsbDevice(getActivity())) {
//                                    startActivityForResult(new Intent(getActivity(), ICDialogActivity2.class),
//                                            REQUEST_CARD_CANCEL);
                                    mPunchState = PunchState.cancel;
                                    IcManager.getInstance().openDevice();
                                    dialogDelegate.changeText("","");
                                    dialogDelegate.changeToProgressType( "正在打开设备...");
                                    dialogDelegate.getDialog().setOnDismissListener(new DialogInterface.OnDismissListener() {
                                        @Override
                                        public void onDismiss(DialogInterface dialog) {
                                            IcManager.getInstance().leisureDevice();
                                        }
                                    });
                                } else {
                                    startActivityForResult(new Intent(getActivity(), NFCDialogActivity.class),
                                            REQUEST_CARD_CANCEL);
                                }
                            }
                        });
                    }

                }
            }

            @Override
            public void onSimpleItemClick(BaseQuickAdapter adapter, View view, int position) {
                TroubleContent troubleContent = operatorAdapter.getItem(position);
                troubleContent.setChecked(!troubleContent.isChecked());
                List<TroubleContent> list = mClockInData.get((int) troubleContent.getTroubleId());
                if (list == null) {
                    list = new ArrayList<>();
                }
                if (troubleContent.isChecked()) {
                    list.add(troubleContent);
                } else {
                    list.remove(troubleContent);
                }
                if (list.isEmpty()) {
                    mClockInData.remove((int) troubleContent.getTroubleId());
                } else {
                    mClockInData.put((int) troubleContent.getTroubleId(), list);
                }
                if (mClockInData.size() > 0) {
                    setClockInButtonEnable(true);
                } else {
                    setClockInButtonEnable(false);
                }
                operatorAdapter.notifyItemChanged(position);
            }

            @Override
            public void onItemChildClick(BaseQuickAdapter adapter, View view, int position) {
                TroubleContent troubleContent = (TroubleContent) adapter.getItem(position);
                if (view.getId() == R.id.btn_delete) {
                    troubleContents.remove(position);
                    adapter.notifyItemRemoved(position);
                    //删除
                    adapter.notifyItemRangeChanged(0, troubleContents.size() - position);
                    //查询
                    long troubleId = troubleContent.getTroubleId();
                    if (troubleId != -1) {
                        mTypeAdapter.updateTroubleState(troubleId, troubleContent);
                    }
                } else if (view.getId() == R.id.iv_add) {
                    troubleContent.setUseCount(troubleContent.getUseCount() + 1);
                    adapter.notifyItemChanged(position, troubleContent);
                } else if (view.getId() == R.id.iv_minus) {
                    if (troubleContent.getUseCount() <= 1) {
                        return;
                    }
                    troubleContent.setUseCount(troubleContent.getUseCount() - 1);
                    adapter.notifyItemChanged(position, troubleContent);
                }
            }
        });

        operatorAdapter = new RepairOperatorAdapter(getActivity(), troubleContents);
        recyclerViewTool.setAdapter(operatorAdapter);
    }

    private void setClockInButtonEnable(boolean isEnable) {
        btnWorkDevice.setEnabled(isEnable);
    }


    public void setPresenter() {
        mPresenter = new RepairPresenter();
        RepairModel mModel = new RepairModel();
        mPresenter.setVM(this, mModel);
    }


    private void setCanOperator(boolean isCan) {
        if (isCan) {
            layoutDevice.setVisibility(View.VISIBLE);
            mBtnCustomAdd.setVisibility(View.VISIBLE);
        } else {
            layoutDevice.setVisibility(View.GONE);
            mBtnCustomAdd.setVisibility(View.GONE);
        }
    }


    @Override
    public void onNetworkError(String msg) {
        dialogDelegate.stopProgressWithFailed(msg, msg);
    }

    @Override
    public void onError(String msg) {
        dialogDelegate.stopProgressWithFailed(msg, msg);
    }

    @Override
    public void onTokenInvalid(String msg) {
        dialogDelegate.stopProgressWithWarning(msg, "请重新登录", new DialogDelegate.OnDialogListener() {
            @Override
            public void onClick() {
                Intent intent = new Intent(getActivity(), LoginActivity.class);
                intent.putExtra("reload", "reload");
                intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
                startActivity(intent);
            }
        });
    }


    /**
     * 添加自定义操作
     */
    public void onAddOperator(Trouble trouble) {
        new ChooseOperatorDialog(getActivity(), DataProvider.getOperationList(), trouble, this).show();
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        mRequestCode = requestCode;
        if (resultCode == ChooseOperatorActivity.RESULT_CODE) {
            ArrayList<ProcessDecorate> list = (ArrayList<ProcessDecorate>) data.
                    getSerializableExtra(ChooseOperatorActivity.EXTRA_NAME);

            ArrayList<TroubleContent> troubleContents = new ArrayList<>();
            for (ProcessDecorate processDecorate : list) {
                troubleContents.add(new TroubleContent().
                        ProcessDecorate2TroubleContent(processDecorate));
            }
            if (operatorAdapter != null) {
                if (operatorAdapter.getData() != null) {
                    operatorAdapter.getData().addAll(troubleContents);
                    int size = operatorAdapter.getData().size();
                    operatorAdapter.notifyItemInserted(size - list.size());
                    operatorAdapter.notifyItemRangeChanged(size - list.size(), list.size());
                }
            }

        } else if (resultCode == PartSearchActivity.RESULT_CODE) {
            String type = data.getStringExtra("type");
            TroubleContent.Part part = (TroubleContent.Part) data.getSerializableExtra("part");
            Trouble trouble = (Trouble) data.getSerializableExtra(PartSearchActivity.TROUBLE);
            long troubleTypeId = trouble.getTroubleTypeId();
            TroubleClassification classification = trouble.getClassification();
            TroubleContent.Operation operation = (TroubleContent.Operation) data.getSerializableExtra("operation");
            TroubleContent troubleContent = new TroubleContent();
            if ("Accessory".equals(type)) {
                troubleContent.setAccessory(part);
            } else {

                troubleContent.setComponent(part);
            }
            troubleContent.setOperation(operation);
            if (classification != null) {
                troubleContent.setClassificationId(classification.getId());
                troubleContent.setClassificationName(classification.getName());
            }
            troubleContent.setTroubleTypeId(troubleTypeId);
            troubleContent.setTroubleId(trouble.getId());
            troubleContent.setTroubleTypeName(trouble.getName());
            troubleContent.setUseCount(1);
            troubleContent.setId(0);
            if (operatorAdapter != null) {
                if (operatorAdapter.getData() != null) {
                    operatorAdapter.getData().add(0, troubleContent);

                    operatorAdapter.notifyItemInserted(0);
                    operatorAdapter.notifyItemRangeChanged(0, 1);
                    recyclerViewTool.scrollToPosition(0);
                    if (!"自定义录入@@".equals(trouble.getName())) {
                        if (mCurrentTrouble != null) {
                            List<TroubleContent> list = mCurrentTrouble.getListContent();
                            if (list == null) {
                                list = new ArrayList<>();
                                mCurrentTrouble.setListContent(list);
                            }
                            list.add(troubleContent);
                            mCurrentTrouble.setChecked(true);
                            mTypeAdapter.notifyDataSetChanged();
                        }
                    }
//
//                    int size = operatorAdapter.getData().size();
//                    operatorAdapter.notifyItemInserted(size - 1);
//                    operatorAdapter.notifyItemRangeChanged(size - 1, 1);
                }
            }
        } else if (resultCode == NFCDialogActivity.NFC_RESULTCODE) {
            byte[] displayContents = data.getByteArrayExtra("BarCodeContents");
            try {
                String contents = new String(displayContents, "utf-8");
                String result = AESUtils.code_desEncrypt(contents);
                if (result.isEmpty()) {
                    ToastUtils.showToast(getActivity(), "保存失败");
                } else {
                    String[] results = result.split("_");
                    if (result.length() < 2) {
                        ToastUtils.showToast(getActivity(), "保存失败");
                    } else {
                        String personNumber = results[0];
                        String personName = results[1];
                        repairInfo = new RepairInfo();
                        repairInfo.setId(busInfo.getId());
                        if (requestCode == REQUEST_CARD_WORK) {//作业打卡
                            List<RepairInfo.ListTroubleBean> ListTroubleBean = new ArrayList<>();
                            //拿来确定有几条
                            List<Trouble> troubleList = repair.getListTrouble();
                            for (Trouble trouble : troubleList) {
                                long troubleId = trouble.getId();
                                RepairInfo.ListTroubleBean troubleBean = new RepairInfo.ListTroubleBean();
                                troubleBean.setId(troubleId);
                                troubleBean.setName(trouble.getName());
                                List<TroubleContent> troubleContents = mClockInData.get((int) troubleId);
                                if (troubleContents != null) {
                                    //插入打卡人信息
                                    for (TroubleContent troubleContent : troubleContents) {
                                        Person person = new Person();
                                        person.setCode(personNumber);
                                        person.setName(personName);
                                        troubleContent.setWorkPerson(person);
                                    }
                                    troubleBean.setListContent(troubleContents);
                                    mClockInData.remove((int) troubleId);
                                } else {
                                    troubleBean.setListContent(new ArrayList<TroubleContent>());
                                }
                                ListTroubleBean.add(troubleBean);
                            }
                            if (mClockInData.size() > 0) {
                                //如果还有剩余数据，那就是自定义录入的，没有trouble分类，放在最后
                                RepairInfo.ListTroubleBean troubleBean = new RepairInfo.ListTroubleBean();
                                List<TroubleContent> list = new ArrayList<>();
                                troubleBean.setName("自定义录入@@");
                                troubleBean.setListContent(list);
                                int key;
                                for (int i = 0; i < mClockInData.size(); i++) {
                                    key = mClockInData.keyAt(i);
                                    List<TroubleContent> troubleContents = mClockInData.get(key);
                                    for (TroubleContent troubleContent : troubleContents) {
                                        Person person = new Person();
                                        person.setCode(personNumber);
                                        person.setName(personName);
                                        troubleContent.setWorkPerson(person);
                                    }
                                    list.addAll(troubleContents);
                                }
                                ListTroubleBean.add(troubleBean);
                            }
                            repairInfo.setListTrouble(ListTroubleBean);
                            repairInfo.setListConfirm(new ArrayList<RepairInfo.ListConfirmBean>());
                            mPresenter.postRepair();
                        } else {//取消打卡
                            if (!mCurrentCancelPunch.getWorkPerson().getCode().equals(personNumber)) {
                                ToastUtils.showToast(getActivity(), "非本作业人无此权限!");
                            } else {
                                mPresenter.cancelPunchCard();
                                dialogDelegate.showProgressDialog(true, "正在提交...");
                            }
                        }
                    }
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }

    @Override
    public String getAuthKey() {
        return SPUtils.getString(getActivity(), SpKey.KEY_AUTH_KEY, "");
    }

    @Override
    public String getRepairInfo() {
        Gson gson = new Gson();
        String str = gson.toJson(repairInfo);
        Log.e("TAG", str);
        return str;
    }

    @Override
    public String getCancelPunchJson() {
        Trouble trouble = new Trouble();
        List<TroubleContent> list = new ArrayList<>();
        list.add(mCurrentCancelPunch);
        trouble.setListContent(list);
        Gson gson = new Gson();
        String str = gson.toJson(trouble);
        Log.e("TAG", str);
        return str;
    }

    @Override
    public long getBusId() {
        return busInfo == null ? 0 : busInfo.getId();
    }

    @Override
    public long getTroubleTypeId() {
        return mCurrentTrouble.getTroubleTypeId();
    }

    @Override
    public String getTroubleName() {
        return mCurrentTrouble.getName();
    }

    @Override
    public void showRepair(Repair repair) {
        troubleContents.clear();
        this.repair = repair;
        try {
            List<Trouble> list = repair.getListTrouble();
            if (list != null) {
                DataProvider.setTroubleList(list);
            } else {
                DataProvider.setTroubleList(null);
                dialogDelegate.clearDialog();
                return;
            }
            //该辆车添加但未提交的操作
            ArrayList<TroubleContent> oldDatas = null;
            if (isCanOperator) {
                oldDatas = (ArrayList<TroubleContent>) SPUtils.getObject(
                        getActivity(), busInfo.getId() + "");
            }
            SparseArray<List<TroubleContent>> sparseArray = new SparseArray<>();
            if (oldDatas != null && !oldDatas.isEmpty()) {
                for (TroubleContent troubleContent : oldDatas) {
                    List<TroubleContent> troubleContents = sparseArray.get((int) troubleContent.getTroubleId());
                    if (troubleContents == null) {
                        troubleContents = new ArrayList<>();
                        sparseArray.put((int) troubleContent.getTroubleId(), troubleContents);
                    }
                    troubleContents.add(troubleContent);
                }
            }
            Map<String, List<Trouble>> map = new HashMap<>();
            //下面显示的已打卡操作列表列表
            for (Trouble trouble : list) {
                //获取问题类型
                if (trouble.getClassification() != null) {
                    String key = trouble.getClassification().getName();
                    if (map.containsKey(key)) {
                        map.get(key).add(trouble);
                    } else {
                        List<Trouble> troubleList = new ArrayList<>();
                        troubleList.add(trouble);
                        map.put(key, troubleList);
                    }
                }
                List<TroubleContent> oldList = sparseArray.get((int) trouble.getId());
                List<TroubleContent> tempList = trouble.getListContent();
                if (tempList != null && !tempList.isEmpty()) {
                    trouble.setChecked(true);
                    for (TroubleContent content : tempList) {
                        if (trouble.getClassification() != null) {
                            content.setClassificationId(trouble.getClassification().getId());
                            content.setClassificationName(trouble.getClassification().getName());
                        } else {
                            //自定义录入没有类型
                            content.setClassificationId(-1);
                            content.setClassificationName("自定义录入");
                        }
                        content.setTroubleTypeId(trouble.getTroubleTypeId());
                        content.setTroubleId(trouble.getId());
                        content.setTroubleTypeName(trouble.getName());
                    }
                    if (oldList != null) {
                        tempList.addAll(oldList);
                    }
                    troubleContents.addAll(tempList);
                } else {
                    if (oldList != null) {
                        trouble.setChecked(true);
                        trouble.setListContent(oldList);
                        troubleContents.addAll(oldList);
                    }
                }
            }
            //自定义录入的
            List<TroubleContent> contentList = sparseArray.get(0);
            if (contentList != null) {
                troubleContents.addAll(contentList);
            }

            List<FaultSection> faultSections = new ArrayList<>();
            for (String key : map.keySet()) {
                FaultSection headSection = new FaultSection(true, key);
                FaultSection listFaults = new FaultSection(map.get(key));
                faultSections.add(headSection);
                faultSections.add(listFaults);
            }
            mTypeAdapter.setNewData(faultSections);
            operatorAdapter.setNewData(troubleContents);
            dialogDelegate.clearDialog();
        } catch (Exception e) {
            e.printStackTrace();
            dialogDelegate.stopProgressWithFailed("数据解析异常", "数据解析异常");
        }

    }

    @Override
    public void postRepairInfoSucceed() {
        if (mRequestCode == REQUEST_CARD_WORK) {
            mClockInData.clear();
        }
        ToastUtils.showToast(getActivity(), "打卡成功!");
        if (operatorAdapter != null) {
            operatorAdapter.notifyDataSetChanged();
        }
        saveUnCommitData();
        refreshData();
        //主界面需要刷新
        OkBus.getInstance().onEvent(HomeActivity.REGISTER_CODE_BACK_REFRESH);
    }

    @Override
    public void showCancelPunchSucceed() {
        dialogDelegate.changeText("","");
        dialogDelegate.stopProgressWithSuccess("取消成功", "取消成功", new DialogDelegate.OnDialogListener() {
            @Override
            public void onClick() {
                dialogDelegate.clearDialog();
            }
        });
        mCurrentCancelPunch.setWorkPerson(null);
        operatorAdapter.notifyDataSetChanged();
    }

    @Override
    public void showProcess(List<Process> list) {
        dialogDelegate.clearDialog();
        mCurrentTrouble.setProcessList(list);
        showSelectOperatorDialog(list);
    }

    @Override
    public void onDestroyView() {
        super.onDestroy();
        saveUnCommitData();
        mPresenter.onDestroy();
        mPresenter = null;
        dialogDelegate.clearDialog();
        dialogDelegate = null;
        operatorAdapter = null;
        this.troubleContents = null;
        mUnBinder.unbind();
        OkBus.getInstance().unRegister(ITEM_SELECT_BUS_TAG);
        EventBus.getDefault().unregister(this);
    }

    private void saveUnCommitData() {
        //保存当前页面未提交的数据
        if (operatorAdapter != null) {
            ArrayList<TroubleContent> troubleContents = new ArrayList<>();
            ArrayList<TroubleContent> list = (ArrayList<TroubleContent>) operatorAdapter.getData();
            for (TroubleContent troubleContent : list) {
                if (troubleContent.getWorkPerson() == null) {
                    troubleContents.add(troubleContent);
                    troubleContent.setChecked(false);
                }
            }
            if (!troubleContents.isEmpty()) {
                SPUtils.putObject(getActivity(), busInfo.getId() + "", troubleContents);
            } else {
                SPUtils.remove(getActivity(), busInfo.getId() + "");
            }
        }
    }

    private void showSelectOperatorDialog(List<Process> list) {
        new SelectOperatorDialog(getActivity(), busInfo, list, mCurrentTrouble, new SelectOperatorDialog.OnOperatorAddListener() {
            @Override
            public void onAddOperator(ProcessDecorate processDecorate) {
                ArrayList<TroubleContent> troubleContents = new ArrayList<>();
                troubleContents.add(new TroubleContent().
                        ProcessDecorate2TroubleContent(processDecorate));
                if (operatorAdapter != null) {
                    if (operatorAdapter.getData() != null) {
                        operatorAdapter.getData().addAll(0, troubleContents);
                        operatorAdapter.notifyItemInserted(0);
                        operatorAdapter.notifyItemRangeChanged(0, 1);
                        recyclerViewTool.scrollToPosition(0);
                        List<TroubleContent> contentList = mCurrentTrouble.getListContent();
                        if (contentList == null) {
                            contentList = new ArrayList<>();
                            mCurrentTrouble.setListContent(contentList);
                        }
                        contentList.addAll(troubleContents);
                        mCurrentTrouble.setChecked(true);
                        mTypeAdapter.notifyDataSetChanged();
                    }
                }
            }
        }, new SelectOperatorDialog.OnOperatorSearchListener() {
            @Override
            public void onSearchOperator(Trouble trouble) {
                onAddOperator(trouble);
            }
        }).show();
    }

    /**
     * 作业打卡
     */
    public static final int MIN_CLICK_DELAY_TIME = 1000;
    private long lastClickTime = 0;

    @OnClick(R.id.btn_work_device)
    public void onDevice() {
        //防止多次点击
        long currentTime = Calendar.getInstance().getTimeInMillis();
        if (currentTime - lastClickTime > MIN_CLICK_DELAY_TIME) {
            lastClickTime = currentTime;
            if (mClockInData.size() > 0) {
                if (UsbUtil.hasUsbDevice(getActivity())) {
//                    startActivityForResult(new Intent(getActivity(), ICDialogActivity2.class),
//                            REQUEST_CARD_WORK);
                    mPunchState = PunchState.work;
                    IcManager.getInstance().openDevice();
                    dialogDelegate.showProgressDialog(true, "正在打开设备...");
                    dialogDelegate.getDialog().setOnDismissListener(new DialogInterface.OnDismissListener() {
                        @Override
                        public void onDismiss(DialogInterface dialog) {
                            IcManager.getInstance().leisureDevice();
                        }
                    });
                } else {
                    startActivityForResult(new Intent(getActivity(), NFCDialogActivity.class),
                            REQUEST_CARD_WORK);
                }
            } else {
                ToastUtils.showToast(getActivity(), "请选择操作项!");
            }
        } else {
            ToastUtils.showToast(getActivity(), "点得太快啦!");
        }
    }

    /**
     * 过检打卡
     */
    @OnClick(R.id.btn_pass_check)
    public void onPassDevice() {
        if (UsbUtil.hasUsbDevice(getActivity())) {
//            startActivityForResult(new Intent(getActivity(), ICDialogActivity2.class),
//                    REQUEST_CARD_PASS);
            mPunchState = PunchState.passCheck;
            IcManager.getInstance().openDevice();
            dialogDelegate.showProgressDialog(true, "正在打开设备...");
            dialogDelegate.getDialog().setOnDismissListener(new DialogInterface.OnDismissListener() {
                @Override
                public void onDismiss(DialogInterface dialog) {
                    IcManager.getInstance().leisureDevice();
                }
            });
        } else {
            startActivityForResult(new Intent(getActivity(), NFCDialogActivity.class),
                    REQUEST_CARD_PASS);
        }
    }

    /**
     * 竣检打卡
     */
    @OnClick(R.id.btn_finish_check)
    public void onFinishDevice() {
        ArrayList<Trouble> list = getPunchTroubleContent();
        if (!checkPass(list)) {
            ToastUtils.showToast(getActivity(), "作业未完成!");
            return;
        }
        CompletePunchCardActivity.startActivity(getActivity(), list, busInfo, mHasCompleteTroubleList);
    }

    private boolean checkPass(ArrayList<Trouble> list) {
        if (list != null) {
            Iterator<Trouble> troubleIterator = list.iterator();
            while (troubleIterator.hasNext()) {
                Trouble t = troubleIterator.next();
                List<TroubleContent> troubleContents = t.getListContent();
                if (troubleContents == null || troubleContents.isEmpty()) {
                    if ("自定义录入@@".equals(t.getName())) {
                        troubleIterator.remove();
                    } else {
                        return false;
                    }
                }
            }
        } else {
            return false;
        }
        return true;
    }

    private ArrayList<Trouble> getPunchTroubleContent() {
        ArrayList<Trouble> list = repair.getListTrouble();
        if (list != null) {
            for (Trouble trouble : list) {
                List<TroubleContent> troubleContents = trouble.getListContent();
                if (troubleContents != null) {
                    Iterator<TroubleContent> iterator = troubleContents.iterator();
                    while (iterator.hasNext()) {
                        TroubleContent t = iterator.next();
                        if (t.getWorkPerson() == null) {
                            iterator.remove();
                        }
                    }
                }
            }
        }
        return list;
    }

    @Subscribe
    public void onRefreshDataEvent(RepairDataRefreshEvent event) {
        mHasCompleteTroubleList.clear();
        mHasCompleteTroubleList.addAll(event.mIds);
        SPUtils.putObject(getActivity(), "completeTroubleList", mHasCompleteTroubleList);
        saveUnCommitData();
        refreshData();
    }

    @Subscribe
    public void onDataClearEvent(DataClearEvent event) {
        SPUtils.remove(getActivity(), "completeTroubleList");
        SPUtils.remove(getActivity(), busInfo.getId() + "");
    }

    @OnClick(R.id.btn_custom_add)
    public void onCustomAdd() {
        Trouble trouble = new Trouble();
        trouble.setId(0);
        trouble.setName("自定义录入@@");
        onAddOperator(trouble);
    }
    @Subscribe()
    public void onICEvent(final OpenIcEvent event) {
        //接收了该事件就拦截掉 不会继续往优先级小于priority的地方传递
        EventBus.getDefault().cancelEventDelivery(event);
        if (!event.isSuccess) {
            getActivity().runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    if (dialogDelegate != null) {
                        dialogDelegate.changeText(event.mTitle, (String) event.mObject);
                    }
                }
            });
        } else {
            byte[] displayContents = (byte[]) event.mObject;
            String[] result = analysisData(new String(displayContents));
            if(result != null){
                switch (mPunchState){
                    case work:
                        workCard(result);
                        break;
                    case passCheck:
                        passWork(result);
                        break;
                    case cancel:
                        cancelWork(result);
                        break;
                }
            }
        }
    }

    private String[] analysisData(String data) {
        String result;
        try {
            result = AESUtils.code_desEncrypt(data);

            if (result.isEmpty()) {
                ToastUtils.showToast(getContext(), "AES解码失败");
                return null;
            }
            String[] results = result.split("_");
            if (result.length() < 2) {
                ToastUtils.showToast(getContext(), "数组长度小于2");
                return null;
            }
            return results;
        }catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    /**
     * 作业打卡
     * @param result
     */
    private void workCard(String[] result) {
        repairInfo = new RepairInfo();
        repairInfo.setId(busInfo.getId());
        String personNumber = result[0];
        String personName = result[1].trim();
        List<RepairInfo.ListTroubleBean> ListTroubleBean = new ArrayList<>();
        //拿来确定有几条
        List<Trouble> troubleList = repair.getListTrouble();
        for (Trouble trouble : troubleList) {
            long troubleId = trouble.getId();
            RepairInfo.ListTroubleBean troubleBean = new RepairInfo.ListTroubleBean();
            troubleBean.setId(troubleId);
            troubleBean.setName(trouble.getName());
            List<TroubleContent> troubleContents = mClockInData.get((int) troubleId);
            if (troubleContents != null) {
                //插入打卡人信息
                for (TroubleContent troubleContent : troubleContents) {
                    Person person = new Person();
                    person.setCode(personNumber);
                    person.setName(personName);
                    troubleContent.setWorkPerson(person);
                }
                troubleBean.setListContent(troubleContents);
                mClockInData.remove((int) troubleId);
            } else {
                troubleBean.setListContent(new ArrayList<TroubleContent>());
            }
            ListTroubleBean.add(troubleBean);
        }
        if (mClockInData.size() > 0) {
            //如果还有剩余数据，那就是自定义录入的，没有trouble分类，放在最后
            RepairInfo.ListTroubleBean troubleBean = new RepairInfo.ListTroubleBean();
            List<TroubleContent> list = new ArrayList<>();
            troubleBean.setName("自定义录入@@");
            troubleBean.setListContent(list);
            int key;
            for (int i = 0; i < mClockInData.size(); i++) {
                key = mClockInData.keyAt(i);
                List<TroubleContent> troubleContents = mClockInData.get(key);
                for (TroubleContent troubleContent : troubleContents) {
                    Person person = new Person();
                    person.setCode(personNumber);
                    person.setName(personName);
                    troubleContent.setWorkPerson(person);
                }
                list.addAll(troubleContents);
            }
            ListTroubleBean.add(troubleBean);
        }
        repairInfo.setListTrouble(ListTroubleBean);
        repairInfo.setListConfirm(new ArrayList<RepairInfo.ListConfirmBean>());
        mRequestCode = REQUEST_CARD_WORK;
        mPresenter.postRepair();
        getActivity().runOnUiThread(new Runnable() {
            @Override
            public void run() {
                if (dialogDelegate != null) {
                    dialogDelegate.changeText("读卡成功", "正在提交...");
                }
            }
        });
    }
    /**
     * 取消打卡
     */
    private void cancelWork(String[] result){
        String number = result[0];
        if (!mCurrentCancelPunch.getWorkPerson().getCode().equals(number)) {
            getActivity().runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    if (dialogDelegate != null) {
                        dialogDelegate.stopProgressWithFailed("提交失败", "非本人不能取消打卡");
                    }
                }
            });
        } else {
            mRequestCode = REQUEST_CARD_CANCEL;
            mPresenter.cancelPunchCard();
            getActivity().runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    if (dialogDelegate != null) {
                        dialogDelegate.changeText("读卡成功", "正在提交...");
                    }
                }
            });
        }
    }
    /**
     * 过检打卡
     */
    private void passWork(String[] result){

    }
}
